package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.News;
import com.example.demo.entity.Question;
import com.example.demo.mapper.NewsMapper;
import com.example.demo.mapper.QuestionMapper;
import com.example.demo.service.IQuestionService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @descreption:
 * @author: xhr
 * @date: 2022/9/03
 */
@RestController
@RequestMapping("/question")
public class QuestionController {
    @Resource
    QuestionMapper questionMapper;
    @Resource
    private IQuestionService questionService;
    //增
    @PostMapping
    public Result<?> save(@RequestBody Question question) {
        question.setTime(new Date());
        questionMapper.insert(question);
        return Result.success();
    }
    // 改
    @PutMapping
    public Result<?> update(@RequestBody Question question) {
        questionMapper.updateById(question);
        return Result.success();
    }
    // 删
    @DeleteMapping("/{id}")
    public Result<?> update(@PathVariable Long id) {
        questionMapper.deleteById(id);
        return Result.success();
    }
    //全查（给其他vue用）
    @GetMapping
    public Result<?> findAll(){
        return Result.success(questionService.list());
    }
    //全(页)查
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(defaultValue = "10") Integer pagesize,
                              @RequestParam(defaultValue = "1") Integer pagenum,
                              @RequestParam(required = false) String search,
                              @RequestParam(required = false) String courseName,
                              @RequestParam(required = false) Integer type,
                              @RequestParam(required = false) Integer courseId) {
//        LambdaQueryWrapper<Question> wrapper = Wrappers.<Question>lambdaQuery();
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like("name", search);
        }
        if (StrUtil.isNotBlank(courseName)) {
            wrapper.eq("course_name", courseName);
        }
        if (type!=null) {
            wrapper.eq("type", type);
        }
        if (courseId!=null) {
            wrapper.eq("course_id", courseId);
        }
        return Result.success(questionMapper.selectPage(new Page<>(pagenum, pagesize), wrapper));
    }

}
